package lib.image.compress;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.text.DecimalFormat;

/**
 * created by Sabirjan on 2017/11/25
 */

public class TuPianYaSuoTools implements OnImageCompressChangeListener, Handler.Callback {


    public static boolean loadLibSuccess = false;
    static {
        try {
            System.loadLibrary("image-compress");
            loadLibSuccess = true;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private ImageUtil imageUtil = null;
    private YaSuoListener mListener;
    private Bitmap bitmap;
    private Handler mHandler;
    private Message message;

    public TuPianYaSuoTools() {
        imageUtil = new ImageUtil();
        bitmap = null;
        message = new Message();
        mHandler = new Handler(Looper.getMainLooper(), this);
    }

    public void YaSuo(final String fileFullPath, final String outPutFullPath, final YaSuoListener listener) throws Exception {
        if (listener == null) {
            throw new NullPointerException("OnImageCompressChangeListener 监听器不能为NULL");
        }
        this.mListener = listener;
        if (TextUtils.isEmpty(fileFullPath)) {
            //  listener.error("目标文件地址错误!");
            message.what = -1;
            message.obj = "目标文件地址错误!";
            mHandler.sendMessage(message);
            return;
        }
        if (TextUtils.isEmpty(outPutFullPath)) {
            // listener.error("输出文件地址错误!");
            message.what = -1;
            message.obj = "输出文件地址错误!";
            mHandler.sendMessage(message);
            return;
        }
        if (outPutFullPath.equals(fileFullPath)) {
            //  listener.error("目标文件和输出文件不能指定同一个文件");
            message.what = -1;
            message.obj = "目标文件和输出文件不能指定同一个文件!";
            mHandler.sendMessage(message);
            return;
        }
        File file = new File(fileFullPath);
        if (!file.exists() || !file.isFile()) {
            //listener.error("目标文件不存在！" + fileFullPath);
            message.what = -1;
            message.obj = "目标文件不存在！";
            mHandler.sendMessage(message);
            return;
        }
        new Thread() {
            @Override
            public void run() {
                super.run();
                Log.e("图片压缩", "分线程 ==> 压缩图片");
                try {
                    bitmap = imageUtil.compressImage(fileFullPath, outPutFullPath, TuPianYaSuoTools.this);
                } catch (Exception ex) {
                    freeBitmap();
                    //  listener.error("图片压缩失败！原因:" + ex.getMessage());
                    message.what = -1;
                    message.obj = "图片压缩失败！原因:" + ex.getMessage();
                    mHandler.sendMessage(message);
                }
                freeBitmap();
            }
        }.start();
    }

    public long getFileSize(String filePath) {
        File file = new File(filePath);
        if (!file.exists() || !file.isFile()) {
            return 0;
        }
        long size = file.length();
        return size;
    }

    public static String GetFileSize(String filePath) {
        String size = "";
        File file = new File(filePath);
        if (file.exists() && file.isFile()) {
            long fileS = file.length();
            DecimalFormat df = new DecimalFormat("#.00");
            if (fileS < 1024) {
                size = df.format((double) fileS) + "BT";
            } else if (fileS < 1048576) {
                size = df.format((double) fileS / 1024) + "KB";
            } else if (fileS < 1073741824) {
                size = df.format((double) fileS / 1048576) + "MB";
            } else {
                size = df.format((double) fileS / 1073741824) + "GB";
            }
        } else if (file.exists() && file.isDirectory()) {
            size = "";
        } else {
            size = "0BT";
        }
        return size;
    }

    public String getImageW_H(String fileName) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        //该属性设置为true只会加载图片的边框进来，并不会加载图片具体的像素点
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(fileName, options);
        String result = options.outWidth + "*" + options.outHeight;
        options = null;
        return result;
    }

    private void freeBitmap() {
        try {
            if (bitmap != null && !bitmap.isRecycled()) {
                bitmap.recycle();

                bitmap = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.gc();
        System.gc();
    }

    @Override
    public void onCompressStart() {

    }

    @Override
    public void onCompressFinish(String filePath) {
        freeBitmap();
        message.what = 0;
        message.obj = filePath;
        mHandler.sendMessage(message);
    }

    @Override
    public void onCompressError(int errorNum, String description) {
        System.out.println("错误代码:" + errorNum + " 错误信息:" + description);
        freeBitmap();
        message.what = -1;
        message.obj = "图片压缩失败！原因:" + description;
        mHandler.sendMessage(message);
    }

    @Override
    public void onCompressChange(int errorNum) {

    }

    @Override
    public boolean handleMessage(Message msg) {

        if (mListener == null) return false;
        String strmsg = msg.obj == null ? "" : msg.obj.toString();
        switch (msg.what) {
            case 0:
                mListener.success(strmsg);
                break;
            case -1:
                mListener.error(strmsg);
                break;
        }
        return false;
    }
}
